package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.commons.ex.ServiceException;
import cn.tedu.csmall.commons.pojo.vo.PageData;
import cn.tedu.csmall.commons.util.PageInfoToPageDataConverter;
import cn.tedu.csmall.commons.web.ServiceCode;
import cn.tedu.csmall.product.mapper.AlbumMapper;
import cn.tedu.csmall.product.mapper.PictureMapper;
import cn.tedu.csmall.product.pojo.entity.Picture;
import cn.tedu.csmall.product.pojo.param.PictureAddNewParam;
import cn.tedu.csmall.product.pojo.vo.AlbumStandardVo;
import cn.tedu.csmall.product.pojo.vo.PictureListItemVO;
import cn.tedu.csmall.product.service.PictureService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class PictureServiceImpl implements PictureService {
    @Autowired
    AlbumMapper albumMapper;

    @Autowired
    PictureMapper pictureMapper;

    @Override
    public void addNew(PictureAddNewParam pictureAddNewParam) {
        log.debug("开始处理【添加图片】的业务，参数:{}",pictureAddNewParam);

        Long albumId = pictureAddNewParam.getAlbumId();
        AlbumStandardVo albumStandardVo = albumMapper.getStandardById(albumId);
        if (albumStandardVo==null){
            String message = "添加图片失败,所属的相册不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureAddNewParam,picture);
        picture.setIsCover(0);

        int rows = pictureMapper.insert(picture);
        if (rows != 1){
            String message = "添加图片失败!服务器忙，请稍后再试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
    }

    @Override
    public PageData<PictureListItemVO> listByAlbumId(Long albumId,Integer pageNum) {
        return listByAlbumId(albumId,pageNum,10);
    }

    @Override
    public PageData<PictureListItemVO> listByAlbumId(Long albumId,Integer pageNum,Integer pageSize) {
        log.debug("开始处理【根据相册ID查询图片列表】业务，参数：{}",albumId);
        PageHelper.startPage(pageNum,pageSize);
        List<PictureListItemVO> list = pictureMapper.listByAlbumId(albumId);
        PageInfo<PictureListItemVO> pageInfo = new PageInfo<>(list);
        PageData<PictureListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        return pageData;
    }
}
